package com.my.login;

import com.my.HttpFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Created by YJH on 2017/7/12 21:07.
 */
public class LoginFilter extends HttpFilter {

    //1.从web.xml文件中获取sessionKey，redirectUrl，uncheckedUrls
    private String sessionKey;
    private String redirectUrl;
    private String uncheckedUrls;

    @Override
    protected void init() {
        ServletContext servletContext = getFilterConfig().getServletContext();

        sessionKey = servletContext.getInitParameter("userSessionKey");
        redirectUrl = servletContext.getInitParameter("rediretPage");
        //  /login/a.jsp, /login/list.jsp, /login/login.jsp, /login/doLogin.jsp
        uncheckedUrls = servletContext.getInitParameter("uncheckedUrls");
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        //1.获取请求的servletPath
        String requestUrl = request.getRequestURL().toString();   //  http://localhost:8080/Day_38/login/list.jsp
        String requestURI = request.getRequestURI();              //  /Day_38/login/list.jsp
        String servletPath = request.getServletPath();            //  /login/list.jsp

        System.out.println("requestUrl：" + requestUrl + "\nrequestURI" + requestURI + "\nservletPath" + servletPath);

        //2.检查1获取的servletPath是否为不需要检查的URL中的一个，若是，则直接放行，方法结束
        List<String> urlList = Arrays.asList(uncheckedUrls.replace(" ", "").split(","));
        if (urlList.contains(servletPath)) {
            filterChain.doFilter(request, response);
            return;
        }

        //3.从session中获取sessionKey对应的值，若值不存在，则重定向到requestUrl
        Object user = request.getSession().getAttribute(sessionKey);
        if (user == null) {
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }

        //4.若存在，则放行，允许访问
        filterChain.doFilter(request, response);
    }

}
